package com.ysd.lis.service.eq.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.entity.eq.EqPatrolTask;
import com.ysd.lis.entity.eq.EqPatrolTaskEq;
import com.ysd.lis.entity.eq.EqPatrolTaskEqSt;
import com.ysd.lis.entity.eq.EqPatrolTaskEqStIt;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.eq.EqPatrolTaskEqMapper;
import com.ysd.lis.mapper.eq.EqPatrolTaskEqStMapper;
import com.ysd.lis.mapper.eq.EqPatrolTaskMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.eq.EqPatrolTaskEqStItService;
import com.ysd.lis.service.eq.EqPatrolTaskEqStService;
import com.ysd.lis.service.eq.EqPatrolTaskService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备巡检任务 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-08-15
 */
@Service
public class EqPatrolTaskServiceImpl extends ServiceImpl<EqPatrolTaskMapper, EqPatrolTask> implements EqPatrolTaskService {

    @Autowired
    private EqPatrolTaskMapper eqPatrolTaskMapper;
    @Autowired
    private EqPatrolTaskEqMapper eqPatrolTaskEqMapper;
    @Autowired
    private EqPatrolTaskEqStMapper eqPatrolTaskEqStMapper;
    @Autowired
    private EqPatrolTaskEqStService eqPatrolTaskEqStService;
    @Autowired
    private EqPatrolTaskEqStItService eqPatrolTaskEqStItService;
    @Autowired
    public SysRuleSetService sysRuleSetService;

    @Override
    public Result findPatrolTaskPageList(CommonPageDto pageParam) {
        Page<EqPatrolTask> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<EqPatrolTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqPatrolTask::getDelFlag, 0);
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getStatus()), EqPatrolTask::getStatus, pageParam.getStatus());
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqPatrolTask::getCode, pageParam.getSeachValue())
                    .or().like(EqPatrolTask::getName, pageParam.getSeachValue()));
        }
        lambdaQueryWrapper.orderByDesc(EqPatrolTask::getCreateTime);
        Page<EqPatrolTask> orderPage = eqPatrolTaskMapper.selectPage(page, lambdaQueryWrapper);
        List<EqPatrolTask> records = orderPage.getRecords();
        for (EqPatrolTask order : records) {
            String maintainStatus = order.getStatus();
            if (!"10".equals(maintainStatus)) {
                Timestamp nextDate = order.getPlanDate();
                if (ToolsUtils.isNotEmpty(nextDate)) {
                    long diff = Math.abs(new Date().getTime() - nextDate.getTime());
                    order.setOverdue(diff / (1000 * 60 * 60 * 24));
                }

            }
        }
        return Result.succ(1, "查询成功", orderPage);
    }

    @Override
    public Result addPatrolTask(EqPatrolTask eqPatrolTask) {
        //添加设备巡检任务
        String a = sysRuleSetService.createRuleCodeList("EqPatrolTaskCode", 1).get(0);
        eqPatrolTask.setCode(a);
        eqPatrolTaskMapper.insert(eqPatrolTask);
        List<EqPatrolTaskEq> patrolTaskEqList = eqPatrolTask.getPatrolTaskEqList();
        if (CollectionUtils.isNotEmpty(patrolTaskEqList)) {
            for (EqPatrolTaskEq eqPatrolTaskEq : patrolTaskEqList) {
                eqPatrolTaskEq.setTaskId(eqPatrolTask.getId());
                //添加设备巡检任务设备
                eqPatrolTaskEqMapper.insert(eqPatrolTaskEq);
                List<EqPatrolTaskEqSt> patrolTaskEqStList = eqPatrolTaskEq.getPatrolTaskEqStList();
                List<EqPatrolTaskEqStIt> patrolTaskEqStItList = eqPatrolTaskEq.getPatrolTaskEqStItList();

                String isNormal = "";
                List<String> noPass = new ArrayList<>();
                List<String> noCheck = new ArrayList<>();
                List<String> isNormales = patrolTaskEqStItList.stream().filter(item -> StringUtils.isNotBlank(item.getIsNormal())).map(EqPatrolTaskEqStIt::getIsNormal).distinct().collect(Collectors.toList());

                if (CollectionUtils.isNotEmpty(isNormales)) {
                    isNormal = "正常";
                    for (String item : isNormales) {
                        if ("异常".equals(item)) {
                            isNormal = item;
                            break;
                        }
                    }
                }
                for (EqPatrolTaskEqStIt eqPatrolTaskEqStIt : patrolTaskEqStItList) {
                    if ("异常".equals(eqPatrolTaskEqStIt.getIsNormal())) {
                        noPass.add(eqPatrolTaskEqStIt.getStandardName());
                    }
                }
                for (EqPatrolTaskEqStIt eqPatrolTaskEqStIt : patrolTaskEqStItList) {
                    if (StringUtils.isBlank(eqPatrolTaskEqStIt.getCheckResult())) {
                        noCheck.add(eqPatrolTaskEqStIt.getStandardName());
                    }
                }
                List<String> noPassEs = noPass.stream().distinct().collect(Collectors.toList());
                eqPatrolTaskEq.setCheckResult(isNormal);
                eqPatrolTaskEq.setNoPass(String.join(",", noPassEs));
                eqPatrolTaskEq.setNoCheck(String.join(",", noCheck));
                eqPatrolTaskEqMapper.updateById(eqPatrolTaskEq);

                //添加巡检任务设备的巡检标准
                for (EqPatrolTaskEqSt eqPatrolTaskEqSt : patrolTaskEqStList) {
                    eqPatrolTaskEqSt.setTaskId(eqPatrolTask.getId());
                    eqPatrolTaskEqSt.setTaskEqId(eqPatrolTaskEq.getId());
                    eqPatrolTaskEqStMapper.insert(eqPatrolTaskEqSt);
                    List<EqPatrolTaskEqStIt> eqPatrolTaskEqStIts = patrolTaskEqStItList.stream().filter(eqPatrolTaskEqStIt -> eqPatrolTaskEqStIt.getStandardId().equals(eqPatrolTaskEqSt.getStandardId())).collect(Collectors.toList());
                    //添加巡检任务设备的巡检标准项
                    if (CollectionUtils.isNotEmpty(eqPatrolTaskEqStIts)) {
                        for (EqPatrolTaskEqStIt eqPatrolTaskEqStIt : eqPatrolTaskEqStIts) {
                            eqPatrolTaskEqStIt.setTaskId(eqPatrolTask.getId());
                            eqPatrolTaskEqStIt.setTaskEqId(eqPatrolTaskEq.getId());
                            eqPatrolTaskEqStIt.setTaskEqStId(eqPatrolTaskEqSt.getId());
                        }
                        eqPatrolTaskEqStItService.saveBatch(eqPatrolTaskEqStIts);
                    }
                }
            }
        }
        return Result.succ(1, "添加成功", eqPatrolTask);
    }

    @Override
    public Result editPatrolTask(EqPatrolTask eqPatrolTask) {
        eqPatrolTaskMapper.updateById(eqPatrolTask);
        List<EqPatrolTaskEq> patrolTaskEqList = eqPatrolTask.getPatrolTaskEqList();
        if (CollectionUtils.isNotEmpty(patrolTaskEqList)) {
            for (EqPatrolTaskEq eqPatrolTaskEq : patrolTaskEqList) {
                List<EqPatrolTaskEqSt> patrolTaskEqStList = eqPatrolTaskEq.getPatrolTaskEqStList();
                List<EqPatrolTaskEqStIt> patrolTaskEqStItList = eqPatrolTaskEq.getPatrolTaskEqStItList();

                String isNormal = "";
                List<String> noPass = new ArrayList<>();
                List<String> noCheck = new ArrayList<>();
                List<String> isNormales = patrolTaskEqStItList.stream().filter(item -> StringUtils.isNotBlank(item.getIsNormal())).map(EqPatrolTaskEqStIt::getIsNormal).distinct().collect(Collectors.toList());

                if (CollectionUtils.isNotEmpty(isNormales)) {
                    isNormal = "正常";
                    for (String item : isNormales) {
                        if ("异常".equals(item)) {
                            isNormal = item;
                            break;
                        }
                    }
                }
                for (EqPatrolTaskEqStIt eqPatrolTaskEqStIt : patrolTaskEqStItList) {
                    if ("异常".equals(eqPatrolTaskEqStIt.getIsNormal())) {
                        noPass.add(eqPatrolTaskEqStIt.getStandardName());
                    }
                }
                for (EqPatrolTaskEqStIt eqPatrolTaskEqStIt : patrolTaskEqStItList) {
                    if (StringUtils.isBlank(eqPatrolTaskEqStIt.getCheckResult())) {
                        noCheck.add(eqPatrolTaskEqStIt.getStandardName());
                    }
                }
                List<String> noPassEs = noPass.stream().distinct().collect(Collectors.toList());
                eqPatrolTaskEq.setCheckResult(isNormal);
                eqPatrolTaskEq.setNoPass(String.join(",", noPassEs));
                eqPatrolTaskEq.setNoCheck(String.join(",", noCheck));
                eqPatrolTaskEqMapper.updateById(eqPatrolTaskEq);


                if (CollectionUtils.isNotEmpty(patrolTaskEqStList)) {
                    eqPatrolTaskEqStService.saveOrUpdateBatch(patrolTaskEqStList);
                }
                if (CollectionUtils.isNotEmpty(patrolTaskEqStItList)) {
                    eqPatrolTaskEqStItService.saveOrUpdateBatch(patrolTaskEqStItList);
                }
            }
        }
        return Result.succ(1, "编辑成功", eqPatrolTask);
    }

    @Override
    public Result findPatrolTaskById(EqPatrolTask eqPatrolTask) {
        EqPatrolTask eqPatrolTask1 = eqPatrolTaskMapper.selectById(eqPatrolTask.getId());
        List<EqPatrolTaskEq> eqPatrolTaskEqs = eqPatrolTaskEqMapper.selectList(new LambdaQueryWrapper<EqPatrolTaskEq>().eq(EqPatrolTaskEq::getTaskId, eqPatrolTask1.getId()).eq(EqPatrolTaskEq::getDelFlag, 0));
        for (EqPatrolTaskEq eqPatrolTaskEq : eqPatrolTaskEqs) {
            List<EqPatrolTaskEqSt> eqPatrolTaskEqSts = eqPatrolTaskEqStMapper.selectList(new LambdaQueryWrapper<EqPatrolTaskEqSt>().eq(EqPatrolTaskEqSt::getTaskEqId, eqPatrolTaskEq.getId()).eq(EqPatrolTaskEqSt::getDelFlag, 0));
            List<EqPatrolTaskEqStIt> eqPatrolTaskEqStIts = eqPatrolTaskEqStItService.list(new LambdaQueryWrapper<EqPatrolTaskEqStIt>().eq(EqPatrolTaskEqStIt::getTaskEqId, eqPatrolTaskEq.getId()).eq(EqPatrolTaskEqStIt::getDelFlag, 0));
            eqPatrolTaskEq.setPatrolTaskEqStList(eqPatrolTaskEqSts);
            eqPatrolTaskEq.setPatrolTaskEqStItList(eqPatrolTaskEqStIts);
        }
        eqPatrolTask1.setPatrolTaskEqList(eqPatrolTaskEqs);
        return Result.succ(1, "查询成功!", eqPatrolTask1);
    }

    @Override
    public Result patrolTaskAnalysis(EqPatrolTask eqPatrolTask) {
        LambdaQueryWrapper<EqPatrolTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EqPatrolTask::getPlanId, eqPatrolTask.getPlanId()).eq(EqPatrolTask::getDelFlag, 0);
        List<EqPatrolTask> taskList = eqPatrolTaskMapper.selectList(queryWrapper);
        Map<String, List<EqPatrolTask>> groupedTasks = taskList.stream().collect(Collectors.groupingBy(task ->  DateUtil.format(DateUtil.date(task.getBeginTime()), "yyyy-MM-dd"), TreeMap::new, Collectors.toList()));
        // 遍历并打印结果
        List<String> dateList=new ArrayList<>();
        List<Integer> yjList=new ArrayList<>();
        List<Integer> sjList=new ArrayList<>();
        List<Integer> wjList=new ArrayList<>();
        groupedTasks.forEach((date, tasks) -> {
            int yj=tasks.size();
            int sj=0;
            int wj=0;
            dateList.add(date);
            for (EqPatrolTask task : tasks) {
            if ("5".equals(task.getStatus())||"10".equals(task.getStatus())){
                sj+=1;
            }
            if ("0".equals(task.getStatus())){
                wj+=1;
            }
            }
            yjList.add(yj);
            sjList.add(sj);
            wjList.add(wj);
        });
        Map<String,Object> map=new HashMap<>();
        map.put("date",dateList);
        map.put("yjList",yjList);
        map.put("sjList",sjList);
        map.put("wjList",wjList);
        return Result.succ(1, "查询成功!", map);
    }

    @Override
    public Result findPatrolTaskByPlanId(EqPatrolTask eqPatrolTask) {
        LambdaQueryWrapper<EqPatrolTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EqPatrolTask::getPlanId, eqPatrolTask.getPlanId());
        queryWrapper.eq(EqPatrolTask::getDelFlag, 0);
        List<EqPatrolTask> eqPatrolTasks = eqPatrolTaskMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功!", eqPatrolTasks);
    }

    @Override
    public Result deletePatrolTask(List<EqPatrolTask> eqPatrolTaskes) {
        List<String> ids = eqPatrolTaskes.stream().map(EqPatrolTask::getId).collect(Collectors.toList());
        eqPatrolTaskMapper.deleteBatchIds(ids);
        eqPatrolTaskEqMapper.delete(new LambdaQueryWrapper<EqPatrolTaskEq>().in(EqPatrolTaskEq::getTaskId, ids).eq(EqPatrolTaskEq::getDelFlag, 0));
        eqPatrolTaskEqStMapper.delete(new LambdaQueryWrapper<EqPatrolTaskEqSt>().in(EqPatrolTaskEqSt::getTaskId, ids).eq(EqPatrolTaskEqSt::getDelFlag, 0));
        eqPatrolTaskEqStItService.remove(new LambdaQueryWrapper<EqPatrolTaskEqStIt>().in(EqPatrolTaskEqStIt::getTaskId, ids).eq(EqPatrolTaskEqStIt::getDelFlag, 0));
        return Result.succ(1, "删除巡检任务成功", "");
    }
}
